$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/buserbrandinfo/list',
        datatype: "json",
        colModel: [
			{ label: 'id', name: 'brandId', index: 'brand_id',align: "center", width: 50, key: true
				// formatter:function(value,options,rowData){
				// 	var brandName=rowData["brandName"];
				// 	var brandId=rowData["brandId"];
				// if(1==1) {
				// 	return "<a  onclick='update("+brandId+")'>"+brandName+"</a>";
				// }
				// }
			},
			// { label: '品牌名称', name: 'brandId', index: 'brandId',align: "center", width: 50,bool:"hidden",
			// 	formatter:function(value,options,rowData){
			// 		var brandName=rowData["brandName"];
			// 		$("#jqGrid").setGridParam().hideCol("brandId");
			// 		return "<a  onclick='update("+value+")'>"+brandName+"</a>";
			// 	}
			// },
			{ label: '品牌名称', name: 'brandName', index: 'brandName',align: "center", width: 80 ,
				formatter:function(value,options,rowData){
					var id=rowData["brandId"];
					return "<a  onclick='update("+id+")'>"+value+"</a>";
				}
			},
			{ label: '总用户', name: 'total',dataType: "int", sortable: true, index: 'total',align: "center", width: 50,
				formatter:function(value,options,rowData){
                    var userId=rowData["userIds"]+",";
                    if( value===null || value=="" ){
                        return "<p>" + 0 + "</p>"
                    }else{
                        //return "<a href=buserinfo.html?brandName=" + encodeURI(userId) + ">" + value + "</a>"
						var id=rowData["brandId"];
						return "<a href=buserinfo.html?brandId=" + id + ">" + value + "</a>"
                    }
				}
			},
			{ label: '会员数', name: 'vipTotal',dataType: "int", sortable: true, index: 'vipTotal',align: "center", width: 50 },
			{ label: '今日用户', name: 'today',dataType: "int", sortable: true, index: 'today',align: "center", width: 50,
				formatter:function(value,options,rowData){
					if( value===null || value=="" ){
						return '0';
					}else{
						return value;
					}
				}
			},
			{ label: '昨日用户', name: 'yesterday',dataType: "int", sortable: true, index: 'yesterday',align: "center", width: 50 ,
				formatter:function(value,options,rowData){
					if( value===null || value=="" ){
						return '0';
					}else{
						return value;
					}
				}
			},
			// { label: '前天用户', name: 'beforeday',dataType: "int", sortable: true, index: 'beforeday',align: "center", width: 80 ,
			// 	formatter:function(value,options,rowData){
			// 		if( value===null || value=="" ){
			// 			return '0';
			// 		}else{
			// 			return value;
			// 		}
			// 	}
			// },
			// { label: '公众号', name: 'tencentTotal', index: 'tencentTotal',align: "center", width: 80 },
			{ label: '文章数', name: 'articleTotal', index: 'articleTotal',align: "center", width: 50 ,formatter:function(value,options,rowData) {
					if (value != 0) {
						var brandName = rowData["brandId"];
						return "<a href=barticleinfo.html?brandName=" + encodeURI(brandName) + ">" + value + "</a>"
					}else{
						return value;
					}
				}
			},
			// { label: '昨日文章', name: 'articleYesterday', index: 'articleYesterday',align: "center", width: 80 },
			// { label: '今日文章', name: 'articleToday', index: 'articleToday',align: "center", width: 80 },
			{ label: '昨日分享', name: 'shareYesterday', index: 'shareYesterday',align: "center", width: 50 },
			{ label: '今日分享', name: 'shareToday', index: 'shareToday',align: "center", width: 50 },
			{ label: '创建人', name: 'createBy', index: 'create_By',align: "center", width: 80 },
			{ label: '创建时间', name: 'createTime', index: 'create_time',align: "center", width: 80 },
			{ label: '状态', name: 'brandOpenStatus', index: 'brandOpenStatus',align: "center", width: 50 ,formatter:function(value,options,rowData) {
				if(value==1){
					return "开放";
				}else{
					return "关闭";
				}
				}
			},
			{ label: '操作', name: '', index: '',align: "center", width: 100 ,formatter:function(value,options,rowData) {
					var brandOpenStatus=rowData["brandOpenStatus"];
					var id=rowData["brandId"];
					var brandName = rowData["brandName"];
					var content = "";
					if(brandOpenStatus==1) {
						content += "<button class='btn btn-primary' onclick=vm.status('"+id+"','0')>" + '关闭' + "</button>";
					}else{
						content += "<button class='btn btn-primary' onclick=vm.status('"+id+"','1')>" + '开放' + "</button>";
					}

					content += "<button class='btn btn-danger' style='margin-left: 8px' onclick=vm.shieldBrand('"+id+"',\'"+brandName+"\')>屏蔽<换成我的></button>";
					return content;
				}
			}
        ],
		viewrecords: true,
		height: "100%",
		rowNum: 12,
		rowList : [12,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
	$.ajax({
		type: "POST",
		async:false,
		url: baseURL + 'sys/buserinfo/getUserGzhList',
		contentType: "application/json",
		success: function(r){
			if(r.code==0){
				//vm.bbrandinfo=r.brandInfo;
				$("#selectUserGzhList").append(
					"<option value=''>全部平台</option>");
				$("#gzhList").append(
					"<option value=''>请选择</option>");
				for(var i=0;i<r.userGzhList.length;i++){
					$("#selectUserGzhList").append(
						"<option value=" + r.userGzhList[i].gzhCode +">"+ r.userGzhList[i].gzhName+"</option>");
					$("#gzhList").append(
						"<option value=" + r.userGzhList[i].gzhCode +">"+ r.userGzhList[i].gzhName+"</option>");
				}
			}
		}
	});

	$.ajax({
		type: "POST",
		async: true,
		url: baseURL + 'sys/buserinfo/getAllCategory',
		contentType: "application/json",
		success: function(r){
			console.log("开始！"+ r);
			console.log(r);
			if(r.code==0){
				$("#bBrandCategory").append(
					"<option value='0'>无（请慎选！选择后将出现在前端）</option>");
				for(var i=0;i<r.bBrandCategory.length;i++){
					$("#bBrandCategory").append(
						"<option value=" + r.bBrandCategory[i].id +">"+ r.bBrandCategory[i].categoryName+"</option>");
				}
			}
			console.log("结束！");
		}
	});
});
setTimeout(function () {
	$.ajax({
		type: "POST",
		async:false,
		url: baseURL + 'sys/bbrandinfo/queryAll',
		contentType: "application/json",
		success: function(r){
			// console.log(r);
			if(r.code==0){
				for(var i=0;i<r.brandInfo.length;i++){
					$("#brandName").append(
						"<option value=" + r.brandInfo[i].brandName +">"+"</option>");
				}
				for(var i=0;i<r.brandInfo.length;i++){
					$("#coverBrand").append(
						"<option value=" + r.brandInfo[i].brandName +">"+"</option>");
				}
				$("#brandNames").scrollTop()
                $("#linkBrandName").scrollTop()
			}
		}
	});
},2000)
	function update(e) {
		var id=e;
		vm.showList = false;
		vm.title = "修改";
		vm.barticletypeinfo = {};
		$("#code").val("");
		$("#type").html("");
		$("#type").nextAll("p").html("");
		$("#supply").html("");
		$("#supply").append(
			"<option  value='999'>"+"请选择"+"</option>");
		$.ajax({
			type: "POST",
			url: baseURL +  'sys/barticletypeinfo/queryAll',
			contentType: "application/json",
			success: function(r){
				if(r.code==0){
					vm.barticletypeinfo=r.barticletypeinfo;
					for(i=0;i<vm.barticletypeinfo.length;i++){
						$("#type").append(
							"<option  value=" + vm.barticletypeinfo[i].articleTypeName + "/>")
						;
						$("#supply").append(
							"<option  value=" + vm.barticletypeinfo[i].id + ">"+vm.barticletypeinfo[i].articleTypeName+"</option>")
						;
						$(".list").append("<p hidden='hidden'  id=" + vm.barticletypeinfo[i].articleTypeName + ">"+vm.barticletypeinfo[i].id+"</p>")
						;
					}
				}
			}
		});
		vm.getInfo(id);
	}
var vm = new Vue({
	el:'#rrapp',
	data:{
		coverBrand: [],
		coverType: [],
		showList: true,
		title: null,
		bUserBrandInfo: {},
		bBrandInfo: {},
		brandinfo :{},
		barticletypeinfo:{},
		typeList:{},
		layero: null,
		q:{
			brandNames:[]
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.bUserBrandInfo = {};
			vm.barticletypeinfo = {};
			vm.bBrandInfo={};
			//设置默认选中第一项
			$("#bBrandCategory option:first").prop("selected", 'selected');
			$("#code").val("");
			$('#in1').html("");
			$("#type").html("");
			$("#type").nextAll("p").html("");
			$("#supply").html("");
			$("#supply").append(
				"<option  value='999'>"+"请选择"+"</option>");
			;
			// $("#type").html("");
			$.ajax({
				type: "POST",
				url: baseURL +  'sys/barticletypeinfo/queryAll',
				contentType: "application/json",
				success: function(r){
					if(r.code==0){
						vm.barticletypeinfo=r.barticletypeinfo;
						for(i=0;i<vm.barticletypeinfo.length;i++){
							$("#type").append(
								"<option  value=" + vm.barticletypeinfo[i].articleTypeName + "/>")
							;
							$("#supply").append(
								"<option  value=" + vm.barticletypeinfo[i].id + ">"+vm.barticletypeinfo[i].articleTypeName+"</option>");
							;
							$(".list").append("<p hidden='hidden'  id=" + vm.barticletypeinfo[i].articleTypeName + ">"+vm.barticletypeinfo[i].id+"</p>")
							;
						}
						$("#supply").find("option[value='" + '' + "']").attr("selected", true);
					}
				}
			});
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var length=$("#code").val();
			if(length<=0){
				// alert("请选择文章类型分类");
				// return;
				length=0;
			}else{
				length=length.substr(0,length.length-1);
			}
			vm.bBrandInfo.articleTypeIds = length;
			console.log(length);
			if(vm.bBrandInfo.brandAlias==null || vm.bBrandInfo.brandAlias==""){
				vm.bBrandInfo.brandAlias="";
			}
			if(vm.bBrandInfo.brandKeyWord==null || vm.bBrandInfo.brandKeyWord==""){
				vm.bBrandInfo.brandKeyWord="";
			}
			if(vm.bBrandInfo.brandName==""||vm.bBrandInfo.brandName==null) {
				alert("请输入品牌名称");
				return;
			}
			// }else if(vm.bBrandInfo.articleTypeIds==""||vm.bBrandInfo.articleTypeIds==null){
			// 	alert("请选择分类");
			// 	return;
			// }else if($('#supply option:selected').val()=="999"){
			// 	alert("请选择内部分类");
			// 	return;
			// }
			vm.bBrandInfo.articleTypeId=$('#supply option:selected').val();
			vm.bBrandInfo.bigCategory=$('#bBrandCategory option:selected').val();
			vm.bBrandInfo.tempContent = window.current_editor.getContent();

			// console.log("window.current_editor.getContent():" + window.current_editor.getContent())
			// console.log("vm.bBrandInfo.tempContent:" + vm.bBrandInfo.tempContent)
			// console.log("tempContent:" + $("#ueditor_0").contents().find("body").html())
			// console.log("JSON.stringify:" + JSON.stringify(vm.bBrandInfo))

			// 组装保存绑定品牌名称
			let pBrandNames = "";
			if ($(".pBrandName").length > 0) {
				$(".pBrandName").each(function () {
					pBrandNames = pBrandNames + "," + $(this).attr("value");
				});
				pBrandNames = pBrandNames.substring(1);
			}
			vm.bBrandInfo.brandBindingNames = pBrandNames;
			vm.bBrandInfo.linkBrandName = $('#linkBrandName').val();

			console.info(vm.bBrandInfo.brandBindingNames);
			var url = vm.bBrandInfo.id == null ? "sys/bbrandinfo/save" : "sys/bbrandinfo/update";
			$.ajax({
				type: "POST",
				url: baseURL + url,
				contentType: "application/json;charset=UTF-8",
				data: JSON.stringify(vm.bBrandInfo),
				dataType: "JSON",
				success: function(r){
					if(r.code === 0){
						alert('操作成功', function(index){
							vm.back();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/buserbrandinfo/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		status:function(e,x){
			vm.bBrandInfo.id=e;
			vm.bBrandInfo.brandOpenStatus=x;
			var msg="";
			if(x==0){
				msg="确认关闭此品牌？"
			}else{
				msg="确认开放此品牌？"
			}
			confirm(msg, function(){
				$.ajax({
					type: "POST",
					url: baseURL + "sys/bbrandinfo/update",
					contentType: "application/json",
					data: JSON.stringify(vm.bBrandInfo),
					success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			//设置默认选中第一项
			$("#brandLogo").attr("src","");
			$("#bBrandCategory option:first").prop("selected", 'selected');

			$.get(baseURL + "sys/buserbrandinfo/info/"+id, function(r){
                vm.bBrandInfo = r.bUserBrandInfo;
				$("#linkBrandName").val("");
                if(vm.bBrandInfo.linkBrandName != null){
					$("#linkBrandName").val(vm.bBrandInfo.linkBrandName);
				}
				$("#brandLogo").attr("src", vm.bBrandInfo.brandLogo);
                vm.typeList=r.list;
				var ids = $("#code").val();
				$('#in1').html("");
				for(var i=0;i<vm.typeList.length;i++){
					console.log(vm.typeList.length)
					$("#in1").append("<a href=# onclick=javascript:deleteCode("+vm.typeList[i].articleTypeIds+");><div style='width:auto;float:left;' id="+vm.typeList[i].articleTypeIds+">"+vm.typeList[i].articleTypeName+';'+" </div></a>");
					$("#"+vm.typeList[i].articleTypeIds).hover(function(){
						$(this).css("background","yellow");},function(){
						$(this).css("background","white");
					});
					//添加隐藏域的值
					ids += vm.typeList[i].articleTypeIds + ",";
					$("#code").val(ids);
				}
				var typeValue=r.typeName;
				console.log(typeValue)
				if(typeValue.length>0) {
					$("#supply").find("option[value='" + typeValue + "']").attr("selected", true);
				}else{
					$("#supply").find("option[value='']").attr("selected", true);
				}

				var bigCategoryValue=vm.bBrandInfo.bigCategory;
				console.log("bigCategoryValue:" +bigCategoryValue)
				if(bigCategoryValue != null && bigCategoryValue > 0) {
					$("#bBrandCategory").find("option[value='" + bigCategoryValue + "']").prop("selected", true);
				}else{
					//设置默认选中第一项
					$("#bBrandCategory option:first").prop("selected", 'selected');
					// $("#bBrandCategory").find("option[value='']").attr("selected", true);
				}

				// 渲染绑定品牌名称
				$(".pBrandName").remove();
				console.info(vm.bBrandInfo.brandBindingNames);
				if (vm.bBrandInfo.brandBindingNames) {
					let bns = new Array(); //定义一数组
					bns = vm.bBrandInfo.brandBindingNames.split(","); //字符分割
					for (let i = 0; i < bns.length; i++) {
						var index = genID(6);//获取6位随机ID
						$("#selectBrandNameList").append("<p class='pBrandName' id='pBrandName" + index + "' value='" + bns[i] + "'>" + bns[i] + "&nbsp;<a href='javascript:void(0);' onclick='delBrand(" + index + ")'>删除</a></p>");
					}
				}

                var a=vm.bBrandInfo.tempContent;
                console.log("Content Load:"+a);
                window.current_editor.setContent(a);
            });
		},
		/**
		 * 屏蔽品牌"换成我的"
		 * @param brandId
		 * @param brandName
		 */
		shieldBrand: function (brandId, brandName) {
			console.log("[brandId] = " + brandId + " [brandName] = " + brandName);

			// 1、传递数据
			$("#shieldBrandId").val(brandId);
			$("#shieldBrandName").val(brandName);
			$("#gzhList").val('');

			// 开窗
			layer.open({
				type: 1,
				title: ['品牌屏蔽<换成我的>', 'font-weight: bold'],
				area: ['600px', '300px'],
				shadeClose: true,
				scrollbar: false,
				content: $('#brandShield'),
				success: function (layero, index) {
					vm.layero = index;
				}
			})
		},
		saveShildBrand: function () {
			let brandId = $("#shieldBrandId").val();
			let gzhCode = $("#gzhList").val();

			if (!gzhCode || gzhCode == '') {
				alert("请选择公众号");
				return;
			}

			let data = {brandId: brandId, gzhCode: gzhCode};

			$.ajax({
				type: "POST",
				url: baseURL + "sys/bbrandshield/save",
				contentType: "application/json;charset=utf8",
				data: JSON.stringify(data),
				success: function (r) {
					if (r.code === 0) {
						alert("屏蔽成功");
					} else {
						alert(r.msg);
					}
				}
			});
		},
		cancle: function () {
			if (vm.layero) {
				layer.close(vm.layero);
			}
		},
		reload: function (event) {
			vm.showList = true;
			var brandName=$("#brandNames").val();
			$("#code").val("");
			$("#type").html("");
			$("#type").nextAll("p").html("");
			var page = 1;
			$("#jqGrid").jqGrid('setGridParam',{
				postData:{'brandName':brandName,'gzhCode': vm.q.gzhCode},
                page:page
            }).trigger("reloadGrid");
		},
		back:function (event) {
			$(".pBrandName").remove();
			vm.showList = true;
			// $("#code").val("");
			// $('#in1').html("");
			$("#code").val("");
			$("#type").html("");
			$("#ueditor_0").contents().find("body").html("");
			$("#type").nextAll("p").html("");
			var brandName=$("#brandNames").val();
			var page =$("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
				postData:{'brandName':brandName},
				page:page
			}).trigger("reloadGrid");
		}
	},
	created:function () {

	}
});
